import { useMemo, useState } from 'react';
import { LinkedList } from '@ds/linked-list';
import { Space, Input, Button, Typography, Card, Tag, Empty, Alert } from 'antd';
import { RightOutlined } from '@ant-design/icons';
import { useLocation } from 'react-router-dom';

function validateListWithTrace(
  values: number[]
): Array<{ index: number; value: number; pass: boolean; reason?: string }> {
  return values.map((v, i) => ({
    index: i,
    value: v,
    pass: Number.isFinite(v),
    reason: Number.isFinite(v) ? undefined : '非有限数字',
  }));
}

export default function LinkedListVisualizer() {
  const [input, setInput] = useState('10,20,30');
  const [opValue, setOpValue] = useState('15');
  const location = useLocation();
  const isOverviewMode = location.pathname === '/list';
  const isValidateMode = location.pathname.startsWith('/list/validate');

  const list = useMemo(() => {
    const ll = new LinkedList<number>();
    input
      .split(/[\s,]+/)
      .filter(Boolean)
      .map(Number)
      .forEach((v) => ll.append(v));
    return ll;
  }, [input]);

  const values = list.toArray();
  const trace = useMemo(() => validateListWithTrace(values), [values]);
  const hasInvalid = useMemo(() => trace.some((t) => !t.pass), [trace]);

  return (
    <Space direction="vertical" size="middle" style={{ width: '100%' }}>
      <Typography.Title level={2}>链表可视化</Typography.Title>

      {isOverviewMode && (
        <Alert
          message="单向链表概述：定义与验证"
          description={
            <Typography.Paragraph style={{ marginBottom: 0 }}>
              定义：由若干节点组成，每个节点包含数据与指向下一个节点的引用，尾节点指向{' '}
              <Typography.Text code>null</Typography.Text>。
              <br />
              验证：本演示按输入数组构造链表，基础验证为“节点值是否为有限数字”，并以序列顺序展示。
            </Typography.Paragraph>
          }
          type="info"
          showIcon
        />
      )}

      {isValidateMode && (
        <Alert
          message="验证过程（节点序列检查）"
          description={
            <Typography.Paragraph style={{ marginBottom: 0 }}>
              逐节点检查：确保每个节点值为有效的有限数字，展示索引与值以及是否通过。
            </Typography.Paragraph>
          }
          type={hasInvalid ? 'warning' : 'success'}
          showIcon
        />
      )}

      <Space>
        <Input
          allowClear
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="例如: 10,20,30"
          style={{ width: 320 }}
        />
        <Input
          allowClear
          value={opValue}
          onChange={(e) => setOpValue(e.target.value)}
          placeholder="操作值，例如: 15"
          style={{ width: 160 }}
        />
      </Space>

      <Space>
        <Button
          onClick={() =>
            setInput((prev) => [opValue, ...prev.split(/[\s,]+/).filter(Boolean)].join(','))
          }
        >
          头插（prepend）
        </Button>
        <Button
          type="primary"
          onClick={() =>
            setInput((prev) => [...prev.split(/[\s,]+/).filter(Boolean), opValue].join(','))
          }
        >
          尾插（append）
        </Button>
      </Space>

      {isValidateMode && (
        <Card title="验证步骤（节点与索引）" size="small">
          {values.length === 0 ? (
            <Empty description="空链表" />
          ) : (
            <div style={{ display: 'grid', rowGap: 8 }}>
              {trace.map((t) => (
                <div key={t.index} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <Tag color={t.pass ? 'green' : 'red'}>{t.pass ? '✓' : '✗'}</Tag>
                  <Typography.Text>
                    节点索引 <Typography.Text code>{t.index}</Typography.Text>，值{' '}
                    <Typography.Text code>{t.value}</Typography.Text>
                  </Typography.Text>
                  {!t.pass && t.reason && (
                    <Tag color="red" style={{ marginLeft: 8 }}>
                      {t.reason}
                    </Tag>
                  )}
                </div>
              ))}
            </div>
          )}
        </Card>
      )}

      <Card title="链表节点" size="small">
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {values.length === 0 ? (
            <Empty description="空链表" />
          ) : (
            values.map((v, i) => (
              <div key={`${v}-${i}`} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <Tag color="blue" style={{ padding: '4px 10px' }}>
                  {v}
                </Tag>
                {i < values.length - 1 && <RightOutlined style={{ color: '#999' }} />}
              </div>
            ))
          )}
        </div>
      </Card>

      <Typography.Text type="secondary">
        提示：本可视化使用 LinkedList.append/prepend 语义，通过 toArray() 派生视图。
      </Typography.Text>
    </Space>
  );
}
